<template>
  <el-dialog
    :title="formType === 'add' ? '新增学生' : '编辑学生'"
    v-model="dialogVisible"
    width="650px"
    @close="handleClose"
    top="5vh"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      label-position="right"
      class="student-form"
    >
      <el-form-item label="学号" prop="studentNo">
        <el-input v-model="form.studentNo" placeholder="请输入学号" clearable />
      </el-form-item>

      <el-form-item label="姓名" prop="fullName">
        <el-input v-model="form.fullName" placeholder="请输入姓名" clearable />
      </el-form-item>

      <el-form-item label="性别" prop="sex">
        <el-radio-group v-model="form.sex">
          <el-radio :label="1">男</el-radio>
          <el-radio :label="0">女</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="班级" prop="classInfoId">
        <el-select
          v-model="form.classInfoId"
          placeholder="请选择班级"
          clearable
          style="width: 100%"
          @change="handleClassChange"
        >
          <el-option
            v-for="item in classList"
            :key="item.id"
            :label="item.classNo"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="电话号码" prop="phoneNumber">
        <el-input
          v-model="form.phoneNumber"
          placeholder="请输入电话号码"
          clearable
        />
      </el-form-item>

      <el-form-item label="面容ID" prop="faceId">
        <el-input v-model="form.faceId" placeholder="请输入面容ID" clearable />
      </el-form-item>

      <el-form-item label="备注" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          placeholder="请输入备注信息"
          :rows="3"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting"
          >提交</el-button
        >
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from "vue";
import { ElMessage } from "element-plus";
import studentApi from "@/api/student";
import classApi from "@/api/class";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  formType: {
    type: String,
    default: "add", // 'add' 或 'edit'
  },
  studentData: {
    type: Object,
    default: () => ({}),
  },
});

const emit = defineEmits(["update:modelValue", "submit-success"]);

// 对话框可见性
const dialogVisible = ref(props.modelValue);

// 表单引用，用于表单验证
const formRef = ref(null);

// 提交状态
const submitting = ref(false);

// 班级列表
const classList = ref([]);

// 表单数据
const form = reactive({
  id: undefined,
  studentNo: "",
  fullName: "",
  sex: 1, // 默认为男性
  classInfoId: undefined,
  className: "",
  phoneNumber: "",
  faceId: "",
  description: "",
});

// 表单验证规则
const rules = {
  studentNo: [
    { required: true, message: "请输入学号", trigger: "blur" },
    { min: 2, max: 30, message: "长度在 2 到 30 个字符", trigger: "blur" },
  ],
  fullName: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
  sex: [{ required: true, message: "请选择性别", trigger: "change" }],
  classInfoId: [{ required: true, message: "请选择班级", trigger: "change" }],
  phoneNumber: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
};

// 监听对话框可见性的变化
watch(
  () => props.modelValue,
  (value) => {
    dialogVisible.value = value;
  }
);

// 监听对话框内部可见性的变化
watch(
  () => dialogVisible.value,
  (value) => {
    emit("update:modelValue", value);
  }
);

// 监听外部传入的学生数据变化
watch(
  () => props.studentData,
  (newVal) => {
    if (newVal && Object.keys(newVal).length > 0) {
      // 将外部传入的数据复制到表单中
      Object.assign(form, newVal);
    }
  },
  { immediate: true, deep: true }
);

// 获取班级列表
const fetchClassList = async () => {
  try {
    const response = await classApi.getClassList(1, 100);
    classList.value = response.list || [];
  } catch (error) {
    console.error("获取班级列表失败:", error);
    ElMessage.error("获取班级列表失败");
  }
};

// 处理班级选择变化
const handleClassChange = (classId) => {
  if (!classId) {
    form.className = "";
    return;
  }

  const selectedClass = classList.value.find((c) => c.id === classId);
  if (selectedClass) {
    form.className = selectedClass.classNo;
  }
};

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false;
  resetForm();
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }

  // 手动清空表单数据
  form.id = undefined;
  form.studentNo = "";
  form.fullName = "";
  form.sex = 1;
  form.classInfoId = undefined;
  form.className = "";
  form.phoneNumber = "";
  form.faceId = "";
  form.description = "";
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid, fields) => {
    if (!valid) {
      console.error("表单验证失败:", fields);
      return;
    }

    submitting.value = true;
    try {
      if (props.formType === "add") {
        // 新增学生
        await studentApi.createStudent(form);
        ElMessage.success("添加成功");
      } else {
        // 编辑学生
        await studentApi.updateStudent(form);
        ElMessage.success("更新成功");
      }

      // 关闭对话框并通知父组件刷新数据
      dialogVisible.value = false;
      emit("submit-success");
      resetForm();
    } catch (error) {
      console.error("提交表单失败:", error);
      ElMessage.error(`提交失败: ${error.message || "未知错误"}`);
    } finally {
      submitting.value = false;
    }
  });
};

// 组件挂载时获取班级列表
onMounted(() => {
  fetchClassList();
});
</script>

<style scoped>
.student-form {
  max-height: 65vh;
  overflow-y: auto;
  padding-right: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
